package com.zqc.login.service;

import com.alibaba.nacos.client.utils.StringUtils;
import com.zqc.login.dao.AuthCodeDao;
import com.zqc.login.pojo.AuthCode;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.joda.time.DateTime;
import org.joda.time.Seconds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.util.Date;
import java.util.Random;

@Service(timeout = 300000)
public class AuthCodeServiceImpl implements AuthCodeService {
    @Autowired
    private AuthCodeDao authCodeDao;

    @Reference
    private EmailService emailService;

    @Value("${authcode.expiretime}")
    private Long expiretime;

    @Override
    public Integer validate(String email, String code) {
        AuthCode authCode = authCodeDao.findByEmailAndCode(email, code);
        if (authCode != null) {
            Seconds seconds = Seconds.secondsBetween(new DateTime(authCode.getExpiretime()), new DateTime(new Date()));
            if (seconds.getSeconds() <= 0) {
               return 0; // 成功
            } else {
                return 2; // 过期
            }
        } else {
            return 1; // 失败
        }
    }

    @Override
    public Boolean create(String email) {
        if (StringUtils.isEmpty(email)) {
            return false;
        }
        DateTime now = DateTime.now();
        String randomCode = buildCode();
        Boolean flag = emailService.sendEmail(email, randomCode);
        if (flag) {
            // 发送成功
            AuthCode authCode = new AuthCode();
            authCode.setEmail(email);
            authCode.setCode(randomCode);
            authCode.setCreatetime(now.toDate());
            authCode.setExpiretime(now.plusMinutes(Integer.valueOf(expiretime.toString())).toDate());
            authCodeDao.saveAndFlush(authCode);
            return true;
        }

        return false;
    }

    /**
     * 生成验证码
     * @return
     */
    private String buildCode() {
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 6; i++) {
            sb.append(random.nextInt(10));
        }
        return sb.toString();
    }
}